<?php
declare (strict_types=1);

namespace app\common\event\listeners\website;

use think\facade\Cache;
use think\Request;

/**
 * 写入访问记录
 */
class Visit
{
    public function handle($data, Request $request)
    {
        $user_id       = $request->mid;
        $mhm_id        = $data['mhm_id'] ?? 0;
        $resource_type = $data['resource_type'];
        $resource_id   = $data['resource_id'];
        $ip            = $request->device_type == 'miniprogram' ? 'miniprogram' . $user_id : $request->ip();

        $datas = [
            'pv' => 1,
        ];

        $redis = Cache::store('redis')->handler();
        // 取得当前IP的访问记录
        $visit = $redis->hGet('visit_datas', $ip);
        if ($visit) {
            $visit = unserialize($visit);
        } else {
            $visit = [];
        }
        // 计算数据key
        $data_key = $mhm_id . '.' . strtotime(date('Y-m-d H:i')) . '.' . $resource_type . '.' . $user_id;
        if (isset($visit[$data_key])) {
            if (isset($visit[$data_key][$resource_id])) {
                // 存在相同资源访问
                $visit[$data_key][$resource_id]['pv'] += 1;
            } else {
                // 不存在访问记录,生成一个
                $visit[$data_key][$resource_id] = $datas;
            }

        } else {
            // 数据结构
            /**
            $visit = [
                '资源类型' => [
                    '资源1' => [
                        'pv' => '访问量',
                        'mhm_id'  => 1,
                        'user_id' => 2,
                        'ip' => $ip
                    ]
                ]
            ];
            缓存IP:127.0.0.1
            缓存值: $visit = [
               '机构.2020-07-13 11:00.资源类型.user_id' =>
                 '资源ID=1' => [
                     'ip' => '127.0.0.1',
                     'pv' => $pv
                 ],
                 '资源ID=2' => [
                     'ip' => '127.0.0.1',
                     'pv' => $pv
                 ]
               ],
               '机构.2020-07-13 11:10.资源类型.user_id' =>
                 '资源ID=1' => [
                     'ip' => '127.0.0.1',
                     'pv' => $pv
                 ],
                 '资源ID=2' => [
                     'ip' => '127.0.0.1',
                     'pv' => $pv
                 ]
               ]
            ];*/
            $visit[$data_key] = [
                $resource_id => $datas,
            ];
        }

        $redis->hSet('visit_datas', $ip, serialize($visit));

    }
}
